package com.atguigu.education.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.education.bean.CourseExamBean;
import com.atguigu.education.util.ClickHouseUtil;
import com.atguigu.education.util.DateFormatUtil;
import com.atguigu.education.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsCourseExamWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // TODO 2
        /*
           env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
           env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
           env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
           env.setStateBackend(new HashMapStateBackend());
           env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
           System.setProperty("HADOOP_USER_NAME", "atguigu");
        */
        // TODO 3 从Kafka中考试主题数据
        String topicName = "dwd_test_exam";
        String groupID = "dws_course_exam_window";
        DataStreamSource<String> courseExamStream = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupID));
        // TODO 4 转换结构为javabean
        SingleOutputStreamOperator<CourseExamBean> beanStream =
                courseExamStream.map(new MapFunction<String, CourseExamBean>() {
                    @Override
                    public CourseExamBean map(String value) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(value);
                        String courseId = jsonObject.getString("course_id");
                        Long score = jsonObject.getLong("score");
                        Long time = jsonObject.getLong("duration_sec");
                        Long ts = DateFormatUtil.toTs(jsonObject.getString("submit_time"), true);
                        return new CourseExamBean("","",courseId,1L,score,time,ts);
                    }
                });
        // TODO 5 设置水位线
        SingleOutputStreamOperator<CourseExamBean> beanWithWatermarkStream = beanStream
                .assignTimestampsAndWatermarks(WatermarkStrategy.<CourseExamBean>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(new SerializableTimestampAssigner<CourseExamBean>() {
                            @Override
                            public long extractTimestamp(CourseExamBean element, long recordTimestamp) {
                                return element.getTs();
                            }
                        }));

        // TODO 6 按试卷id分组
        KeyedStream<CourseExamBean, String> keyedStream = beanWithWatermarkStream.keyBy(new KeySelector<CourseExamBean
                , String>() {
            @Override
            public String getKey(CourseExamBean value) throws Exception {
                return value.getCourseId();
            }
        });

        // TODO 7 开窗聚合
        SingleOutputStreamOperator<CourseExamBean> reducedStream =
                keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                        .reduce(new ReduceFunction<CourseExamBean>() {
                            @Override
                            public CourseExamBean reduce(CourseExamBean value1, CourseExamBean value2) throws Exception {
                                value1.setScore(value1.getScore() + value2.getScore());
                                value1.setTime(value1.getTime() + value2.getTime());
                                value1.setCount(value1.getCount() + value2.getCount());
                                return value1;
                            }
                        }, new WindowFunction<CourseExamBean, CourseExamBean, String, TimeWindow>() {
                            @Override
                            public void apply(String s, TimeWindow window, Iterable<CourseExamBean> input, Collector<CourseExamBean> out) throws Exception {
                                CourseExamBean courseExamBean = input.iterator().next();
                                courseExamBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                                courseExamBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                courseExamBean.setTs(System.currentTimeMillis());
                                out.collect(courseExamBean);
                            }
                        });
        // TODO 8 写出到clickhouse
        reducedStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_course_exam_window values" +
                "(?,?,?,?,?,?,?)"));
        // TODO 9 执行任务
        env.execute(groupID);
    }
}
